package com.tj.jinzao.utils;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;


import java.util.List;
import java.util.Locale;

public class GetLocationUtils {
    public static Geocoder sGeocoder;    //获取并解析位置用
    public static Context sContext;

    public static void getCityByLocation(Context context){
        sContext = context.getApplicationContext();
        sGeocoder = new Geocoder(context, Locale.getDefault());
        LocationManager locationManager;        //管理Location及其他信息
        String serviceName = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) context.getSystemService(serviceName);
        //privider类型
        String provider = LocationManager.NETWORK_PROVIDER;
        //定位设置
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_LOW);//低精度
        criteria.setAltitudeRequired(false);//不要求海拔
        criteria.setBearingRequired(false);//不要求方位
        criteria.setCostAllowed(false);//不允许资费
        criteria.setPowerRequirement(Criteria.POWER_LOW);//低耗电

        Location location = null;
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            location = locationManager.getLastKnownLocation(provider);
            //获取位置需要访问Google提供的服务进行位置解析，比较耗时所以就放在task中，（其实在Android6.0及以下，可以直接放在主线程中执行，Android8.0必须放在Task中）
            new GetCityNameByGeocoder(context,sGeocoder).execute(location);
            //第一个参数提供的类型，第二个参数更新周期(毫秒)，第三个最小距离间隔500m
            locationManager.requestLocationUpdates(provider,300000,500,sLocationListener);
        }else {
            ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
        }
    }

    private final static LocationListener sLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            //获取位置需要访问Google提供的服务进行位置解析，比较耗时所以就放在task中，（其实在Android6.0及以下，可以直接放在主线程中执行，Android8.0必须放在Task中）
            new GetCityNameByGeocoder(sContext,sGeocoder).execute(location);
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    public static class GetCityNameByGeocoder extends AsyncTask<Location,Void,String> {
        private Context context;
        private Geocoder geocoder;
        private RecyclerView weatherrecycler;

        public GetCityNameByGeocoder(Context context, Geocoder geocoder) {
            this.context = context;
            this.geocoder = geocoder;
            this.weatherrecycler = weatherrecycler;
        }

        @Override
        protected String doInBackground(Location... locations) {
            return getCityName(locations[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null){//返回的城市不为空，执行请求天气Task
                Log.i("wjy","city:"+s);
//                new GetWeatherInfoTask(context,weatherrecycler).execute(s);
            }
        }

        private String getCityName(Location location){
            String tmpCity = "";
            double lat = 0;
            double lng = 0;
            List<Address> addressList = null;
            if (location != null){
                lat = location.getLatitude();
                lng = location.getLongitude();
            }else {
                tmpCity = null;
            }
            try {
                //此处访问Google的位置服务，需要放在异步线程中
                addressList = geocoder.getFromLocation(lat,lng,1);
            }catch (Exception e){
                e.printStackTrace();
            }
            if (addressList != null && addressList.size() >0){
                Address address = addressList.get(0);
                //获取目标城市
                String subCity = address.getSubLocality();
                tmpCity = address.getLocality();
            }
            if (tmpCity.length() > 0 && !"".equals(tmpCity)){
                tmpCity = tmpCity.substring(0,(tmpCity.length() - 1));
            }
            return tmpCity;
        }
    }

}